<?php
	session_start();
	include 'base_config.php';
	if (isset($_POST['sessionid'])) {
		$session_id = $_POST['sessionid'];
		$session_id =  mysql_real_escape_string($session_id);
		
		if ($session_id === session_id()) {
			// Local onde o ficheiro vai ser colocado
			$target_path = "../logos/";
			
			//Dados	
			$bookmarkName = $_POST['txtBookmarkName'];
			$bookmarkURL = $_POST['txtBookmarkURL'];
			$bookmarkDescription = $_POST['txtBookmarkDescription'];
			if (isset($_POST['cbActive'])) {
				$active = $_POST['cbActive'];
			} else {
				$active = false;
			}
	
			$bookmarkName =  mysql_real_escape_string($bookmarkName);
			$bookmarkURL = mysql_real_escape_string($bookmarkURL);
			$bookmarkDescription =  mysql_real_escape_string($bookmarkDescription);
			$active = mysql_real_escape_string($active);
			utf8_encode($bookmarkName);
			utf8_encode($bookmarkDescription);
		
			if ($active == true) {
				$active = 1;
			} else {
				$active = 0;
			}
			
			$lastId = 0;
			
			$sql = "INSERT INTO `bookmark` (`bookmarkName`, `bookmarkURL`, `bookmarkDescription`, `active`) VALUES ('$bookmarkName', '$bookmarkURL', '$bookmarkDescription', $active)";
			$result = mysql_query($sql);
			$lastId = mysql_insert_id();
			if (!$result) {
				die('Invalid query: ' . $active . ' - ' . mysql_error());
			} else if ($_FILES['logo']['size'] > 0) {
				/* Add the original filename to our target path.  
				Result is "uploads/filename.extension" */
				$nomeFicheiro = pathinfo($_FILES["logo"]["name"], PATHINFO_FILENAME);
				$ext = pathinfo($_FILES["logo"]["name"], PATHINFO_EXTENSION);
				$novo_nome = $lastId . "." . $ext;

				$bookmarkImagePath = "logos/" . $novo_nome;
				move_uploaded_file($_FILES['logo']['tmp_name'], $target_path . $novo_nome);
				
				$sql = "UPDATE `bookmark` SET `bookmarkImagePath` = '$bookmarkImagePath' WHERE `bookmark`.`idBookmark` = $lastId;";
				$result = mysql_query($sql);
				if (!$result) {
					die('Invalid query: ' . mysql_error());
				} else {				
					$tmp = '{"newID":"' . $lastId . '","Success":"true"}';
					echo $tmp;
				}
			} else {
				$tmp = '{"newID":"' . $lastId . '","Success":"true"}';
				echo $tmp;
			}
			mysql_close($connect);
		} else {
			$tmp = '{"newID":"0","Success":"false"}';
			echo $tmp;
			session_unset();
			session_destroy();
		}
	}